package com.sgb.knowledgeshare.view.fragment;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.android.material.tabs.TabLayout;
import com.sgb.knowledgeshare.R;
import com.sgb.knowledgeshare.databinding.FragmentSharehomeBinding;
import com.sgb.knowledgeshare.entity.ShareUserInfoEntity;
import com.sgb.knowledgeshare.utils.PageChangeSharePublicEvent;
import com.sgb.knowledgeshare.utils.RxBus;
import com.sgb.knowledgeshare.utils.SharePermissionUtils;
import com.sgb.knowledgeshare.view.activity.HomeShareActivity;
import com.sgb.knowledgeshare.view.activity.ShareRecoedVideoActivity;
import com.sgb.knowledgeshare.view.activity.ShareUserActivity;
import com.sgb.knowledgeshare.viewmodel.ShareHomeModel;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.model.entity.VideoBean;
import com.swgk.core.recyclerview.adapter.FragPagerAdapter;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;

import rx.functions.Action1;

/**
 * 主页fragment
 */
public class ShareHomeFragment extends AppLazyFragment {

    ShareHomeModel viewmode;
    /**
     * 默认显示第一页推荐页
     */
    public static int curPage;
    private ArrayList<Fragment> mChildFragments;

    private float slideOffset;
    private FragmentSharehomeBinding binding;

    public static ShareHomeFragment newInstance(int index) {
        ShareHomeFragment fragment = new ShareHomeFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("index", index);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_sharehome, container, false);
        viewmode = new ViewModelProvider(this).get(ShareHomeModel.class);
        viewmode.setActivity(ShareHomeFragment.this);
        binding.setViewModel(viewmode);
        return binding.getRoot();
    }

    public void updateBottomViews(float slideOffset, String userno) {
        this.slideOffset = slideOffset;
        binding.bottomLayout.setAlpha(slideOffset);
        binding.tabLayout.setVisibility(slideOffset == 1 ? View.GONE : View.VISIBLE);
        binding.bottomLayout.setVisibility(slideOffset == 1 ? View.VISIBLE : View.GONE);
        ((HomeShareActivity) getActivity()).updateViewPager(binding.tabLayout.getSelectedTabPosition(), slideOffset);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initView() {
        int index = getArguments().getInt("index");
        mChildFragments = new ArrayList<>();
        mChildFragments.add(new ShareMianFragment());
        mChildFragments.add(new ShareClassifyFragment());
        mChildFragments.add(new ShareMessageFragment());
        mChildFragments.add(new ShareMineFragment());
        FragPagerAdapter slidingFragmentPagerAdapter = new FragPagerAdapter(getChildFragmentManager(), mChildFragments);
        binding.viewpager.setAdapter(slidingFragmentPagerAdapter);
        binding.viewpager.setNoScroll(true);
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) binding.viewpager.getLayoutParams();
                if (tab.getPosition() > 0) {
                    binding.tabLayout.setBackgroundColor(Color.parseColor("#000000"));
                    layoutParams.bottomMargin = binding.tabLayout.getHeight();
                    binding.bottomLayout.setAlpha(0);
                } else {
                    binding.tabLayout.setBackgroundColor(Color.parseColor("#50000000"));
                    layoutParams.bottomMargin = 0;
                    binding.bottomLayout.setAlpha(slideOffset);
                }
                binding.viewpager.setLayoutParams(layoutParams);
              /*  if (tab.getPosition()!=2){
                    ((HomeShareActivity) getActivity()).updateViewPager(tab.getPosition(), slideOffset);
                }*/
                switch (tab.getPosition()) {
                    case 0://首页
                        curPage = tab.getPosition();
                    case 1://分类
                        curPage = tab.getPosition();
                        binding.viewpager.setCurrentItem(tab.getPosition(), false);
                        break;
                    case 2://录制
                        if (PermissionsUtil.hasPermission(getActivity(), SharePermissionUtils.BASIC_EXTERNAL_STORAGE)) {
                            startVido();
                        } else {
                            PermissionsUtil.requestPermission(getActivity(), new PermissionListener() {
                                @Override
                                public void permissionGranted(@NonNull String[] permissions) {
                                    startVido();
                                }
                                @Override
                                public void permissionDenied(@NonNull String[] permissions) {
                                }
                            }, SharePermissionUtils.BASIC_EXTERNAL_STORAGE);
                        }
                        break;
                    case 3://消息
                        if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                            if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                                curPage = tab.getPosition();
                                binding.viewpager.setCurrentItem(tab.getPosition() - 1, false);
                            } else {
                                binding.tabLayout.getTabAt(curPage).select();
                                MToast.showToast(getContext(), "请实名认证完成后再进行点赞！");
                            }
                        } else {
                            binding.tabLayout.getTabAt(curPage).select();
                            MToast.showToast(getContext(), "请先登录账户！");
                        }

                        break;
                    case 4://我的
                        if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                            if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                                binding.viewpager.setCurrentItem(tab.getPosition() - 1, false);
                                curPage = tab.getPosition();
                            } else {
                                binding.tabLayout.getTabAt(curPage).select();
                                MToast.showToast(getContext(), "请实名认证完成后再进行点赞！");
                            }
                        } else {
                            binding.tabLayout.getTabAt(curPage).select();
                            MToast.showToast(getContext(), "请先登录账户！");
                        }
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        //发布视频成功后返回到首页的操作
        RxBus.getDefault().toObservable(PageChangeSharePublicEvent.class)
                .subscribe((Action1<PageChangeSharePublicEvent>) event -> {
                    binding.tabLayout.getTabAt(event.getPage()).select();
                    if (binding.viewpager != null) {
                        binding.tabLayout.getTabAt(event.getPage()).select();
                    }
                });
        binding.bottomLayout.setAlpha(0);
        binding.bottomLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                return slideOffset == 1;
            }
        });
        binding.tabLayout.getTabAt(index).select();
    }

    private void startVido() {
        if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                binding.tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.black));
                ShareRecoedVideoActivity.start(getActivity(), "");
            } else {
                binding.tabLayout.getTabAt(curPage).select();
                MToast.showToast(getContext(), "请实名认证完成后再进行点赞！");
            }
        } else {
            binding.tabLayout.getTabAt(curPage).select();
            MToast.showToast(getContext(), "请先登录账户！");
        }
    }

    @Override
    protected void onLazyLoad() {

    }

    @Override
    public void onVisible() {
        super.onVisible();
        if (curPage == 0) {
            if (mChildFragments != null && mChildFragments.size() > 0) {
                Fragment fragment = mChildFragments.get(curPage);
                if (fragment != null) {
                    if (fragment instanceof ShareMianFragment) {
                        ((ShareMianFragment) fragment).onVisible();
                    }
                }
            }
        }
    }

    @Override
    public void onInvisible() {
        super.onInvisible();
        if (curPage == 0) {
            if (mChildFragments != null && mChildFragments.size() > 0) {
                Fragment fragment = mChildFragments.get(curPage);
                if (fragment != null) {
                    if (fragment instanceof ShareMianFragment) {
                        ((ShareMianFragment) fragment).onInvisible();
                    }
                }
            }
        }

    }

    public void setUserVideoListData(ShareUserInfoEntity records) {
        switch (records.getIsFollow()) {
            case 0:
                binding.fansState.setText("关注");
                binding.fansState.setBackgroundColor(getResources().getColor(R.color.color_5792FD));
                break;
            case 1:
                binding.fansState.setText("取消关注");
                binding.fansState.setBackgroundColor(getResources().getColor(R.color.color_C0C4CC));
                break;
            case 2:
                binding.fansState.setText("互相关注");
                binding.fansState.setBackgroundColor(getResources().getColor(R.color.color_FFC000));
                break;
        }
    }

    public void UpdataUserIfno(String userNo) {
        viewmode.getUserHomePahe(userNo);
    }

    public void updataUserInfos(VideoBean recordsBean, int total) {
        if (recordsBean == null) {
            return;
        }
        Glide.with(getActivity()).load(recordsBean.getHeadImg())
                .apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.mipmap.share_def_photo))
                .into(binding.userLogo);
        binding.userNames.setText(recordsBean.getCreateUserName() + "");
        binding.userCreateNumber.setText("作品" + total);
        switch (recordsBean.getIsFollow()) {
            case 0:
                binding.fansState.setText("关注");
                binding.fansState.setBackgroundColor(getResources().getColor(R.color.color_5792FD));
                break;
            case 1:
                binding.fansState.setText("取消关注");
                binding.fansState.setBackgroundColor(getResources().getColor(R.color.color_C0C4CC));
                break;
            case 2:
                binding.fansState.setText("互相关注");
                binding.fansState.setBackgroundColor(getResources().getColor(R.color.color_FFC000));
                break;
        }
        binding.fansState.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                        //请求接口数据、成功后再获取数据
                        viewmode.getFens(recordsBean.getCreateUser());
                    } else {
                        MToast.showToast(getContext(), "请实名认证完成后再进行点赞！");
                    }
                } else {
                    MToast.showToast(getContext(), "请先登录账户！");
                }
            }
        });
        binding.userLogo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                        //跳转到当前用户的用户中心界面
                        ShareUserActivity.start(getActivity(), recordsBean.getCreateUser());
                    } else {
                        MToast.showToast(getContext(), "请实名认证完成后再进行点赞！");
                    }
                } else {
                    MToast.showToast(getContext(), "请先登录账户！");
                }
            }
        });
    }
}
